import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  // data里的变量与计算属性的关系
  state: {
    name: '123测试',
    newName: 123,
    a: 1,
    b:2,
    c:4,
    list: [],
    detail: null,
    agreeList: []
  },
  getters: {
    newName(state) {
      return state.name + state.newName
    }
  },
  mutations: {
    // (同步)修改state
    setName(state, val) {
      console.log(val)
      state.name = val
    },
    setList(state, val) {
      state.list = val
    },
    getDetailData(state, id) {
      // 同步修改state
      // 查找到详情，存到state里面
      for(let i =0; i< state.list.length; i++) {
        if(state.list[i].article_id == id) {
          state.detail = state.list[i]
        }
      }
    },
    setAgreeData(state, data) {
      state.agreeList = data
    }
  },
  actions: {
    // 处理异步的修改state
    fetchIndexData({commit}, text) {
      axios.get(`/index/page?type=${text}`).then(res => {
          // ctx.state.list = res.data.data.data
          commit('setList', res.data.data.data)
      })
    },
    fetchAgreeData({commit}) {
      // 获取点赞列表
      axios.get('/agree/list').then(res => {
        if(res.data.code == 1) {
          commit('setAgreeData', res.data.data)
        } else{
          alert('请求失败')
        }
      })
    },
    agree({commit, dispatch}, data) {
      axios.post('/agree', data).then(res => {
        if(res.data.code === 1) {
          // 点赞成功
          console.log('点赞成功')
        } else {
          console.log('点赞失败')
        }
        // 更新一下本地的点赞数据
        dispatch('fetchAgreeData')
      })
    }
  },
  modules: {
  },
})
